//
//  XAContentView.swift
//  XAPageViewDemo
//
//  Created by XangAm on 2017/12/28.
//  Copyright © 2017年 Lan. All rights reserved.
//

import UIKit

fileprivate let kContentViewCellIdentifier = "ContentViewCell"

protocol XAContentViewDelegate : class{
    
    func contentView(_ contentView : XAContentView?,selectedIndex : Int) ->Void
    func contentView(_ contentView : XAContentView?,contentViewScrolling  selectedIndex : Int ,nextIndex : Int,progress : CGFloat) ->Void
    
}

class XAContentView: UIView {
    open weak var delegate : XAContentViewDelegate? = nil
    
    fileprivate var style    : XAPageViewStyle
    fileprivate var childVcs : [UIViewController]
    fileprivate var startOffsetX    : CGFloat
    fileprivate var selectedIndex   : Int
    fileprivate var isDealScrolling : Bool
    fileprivate weak var parentVc  : UIViewController?
    fileprivate lazy var collectionView : UICollectionView = {
        let layout : UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: bounds.width, height: bounds.height)
        layout.minimumLineSpacing      = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        
        let collectionView : UICollectionView = UICollectionView(frame: bounds, collectionViewLayout: layout)
        collectionView.bounces         = false
        collectionView.isPagingEnabled = true
        collectionView.scrollsToTop    = false
        collectionView.delegate   = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kContentViewCellIdentifier)
        return collectionView
    }()

    init(frame : CGRect,parentVc : UIViewController?,style : XAPageViewStyle, childVcs : [UIViewController]) {
        self.style = style
        self.childVcs = childVcs
        self.parentVc = parentVc
        self.startOffsetX   = 0
        self.selectedIndex  = 0
        self.isDealScrolling  = true
        super.init(frame: frame)
        setupSubviews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        return nil
    }
    
}

//MARK: - Setup
extension XAContentView {
    fileprivate func setupSubviews(){
        addSubview(collectionView)
        
        for chidVc in childVcs{
            parentVc?.addChildViewController(chidVc)
        }
    }
}

//MARK: - Deal
extension XAContentView {
    fileprivate func dealScrollDidEnd(){
        //纪录滑动结束后的offsetX值
        startOffsetX = collectionView.contentOffset.x
        
        let currentIndex = Int(collectionView.contentOffset.x / collectionView.bounds.width)
        guard  currentIndex != selectedIndex else {
            return
        }
        selectedIndex = currentIndex
        delegate?.contentView(self, selectedIndex: Int(selectedIndex))
        
    }
    fileprivate func dealScrollWillBegin(){
        isDealScrolling = true
        
    }
    
    fileprivate func dealScrolling(){
        let currentOffsetX = collectionView.contentOffset.x ,contentViewW =  collectionView.bounds.width
        
        //计算SelectedIndex
        let selectedIndex : Int = Int(startOffsetX / contentViewW )
        let locationPage  : CGFloat = currentOffsetX / contentViewW
        
        var nextIndex : Int = 0
        var progress  : CGFloat = 0
        //判断是左滑还是右滑计算NextIndex
        if startOffsetX <= currentOffsetX{//左滑
            nextIndex = min(selectedIndex + 1,childVcs.count - 1)
            progress  = CGFloat((currentOffsetX - startOffsetX) / contentViewW)
            //每次滚动到下一个Cell的时候就需要重新纪录 startOffsetX
            if selectedIndex < Int(locationPage){
                startOffsetX = CGFloat(nextIndex) * contentViewW
            }
        }else{//右滑
            progress  = CGFloat((startOffsetX - currentOffsetX) / contentViewW)
            nextIndex = max(selectedIndex - 1, 0)
            //每次滚动到上一个Cell的时候就需要重新纪录 startOffsetX
            if CGFloat(nextIndex) >= locationPage{
                startOffsetX = CGFloat(nextIndex) * contentViewW
            }
        }
        
        
//        print("startOffsetX:\(startOffsetX) selectIndex:\(selectedIndex),nextIndex:\(nextIndex),progress:\(progress)")
        self.delegate?.contentView(self, contentViewScrolling: selectedIndex, nextIndex: nextIndex, progress: progress)
    }

}


//MARK: - <UICollectionViewDelegate>
extension XAContentView : UICollectionViewDelegate{
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        dealScrollDidEnd()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate{
            dealScrollDidEnd()
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if isDealScrolling{
             dealScrolling()
        }
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        dealScrollWillBegin()
    }
    
   
}


//MARK: - <UICollectionViewDataSource>
extension XAContentView : UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return childVcs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell =  collectionView.dequeueReusableCell(withReuseIdentifier: kContentViewCellIdentifier, for: indexPath)
        
        cell.contentView.backgroundColor = UIColor.rondomColor
        //设置数据
        for subview in cell.contentView.subviews{
            subview .removeFromSuperview()
        }
        let childVc = childVcs[indexPath.item]
        cell.contentView.addSubview(childVc.view)
        return cell
    }
}


//MARK: - <XATitleViewDelegate>
extension XAContentView : XATitleViewDelegate{
    func titleView(_ titleView: XATitleView, selectedIndex: Int) {
        isDealScrolling = false
        let indexPath = IndexPath(item: selectedIndex, section: 0)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
    }
}

